const copy = {
  beforeMount(el, { value }) {
    el.$value = value;
    el.handler = () => {
      if (!el.$value) {
        console.log("复制内容为空");
        return;
      }
      const textarea = document.createElement("textarea");
      textarea.readOnly = "readonly";
      textarea.style.position = "absolute";
      textarea.style.left = "-9999px";
      textarea.value = el.$value;
      document.body.appendChild(textarea);
      textarea.select();
      if (navigator.clipboard) {
        navigator.clipboard.writeText(el.$value).then(() => {
          console.log("复制成功", el.$value);
        });
      } else {
        // execCommand即将被废弃
        const result = document.execCommand("Copy");
        if (result) {
          console.log("复制成功", el.$value);
        }
      }
      document.body.removeChild(textarea);
    };
    el.addEventListener("click", el.handler);
  },
  updated(el, { value }) {
    el.$value = value;
  },
  unmounted(el) {
    el.removeEventListener("click", el.handler);
  },
};

export default copy;